import time
import logging
from threading import Lock
from typing import List, Dict, Optional, Any

# 修复: 恢复为标准的绝对路径导入
from app.core.config import settings

logger = logging.getLogger(__name__)

class CredentialWrapper:
    def __init__(self, cred_id: int, credential: Dict[str, str]):
        self.id = cred_id
        self.credential = credential
        self.failure_count = 0
        self.last_used_time = 0
        self.is_resting = False
        self.resting_until = 0

    def __repr__(self):
        return (f"Credential(id={self.id}, failures={self.failure_count}, "
                f"is_resting={self.is_resting})")

class CredentialManager:
    def __init__(self):
        self.credentials: List[CredentialWrapper] = [
            CredentialWrapper(i, cred) for i, cred in enumerate(settings.CREDENTIALS)
        ]
        self.lock = Lock()
        self.current_index = 0
        self.total_requests = 0
        self.total_failures = 0
        self.MAX_FAILURES = 3
        self.RESTING_PERIOD = 60  # seconds

    def get_credential(self) -> Optional[CredentialWrapper]:
        with self.lock:
            if not self.credentials:
                return None

            for _ in range(len(self.credentials)):
                wrapper = self.credentials[self.current_index]
                self.current_index = (self.current_index + 1) % len(self.credentials)

                if wrapper.is_resting and time.time() < wrapper.resting_until:
                    continue

                if wrapper.is_resting:
                    wrapper.is_resting = False
                    wrapper.failure_count = 0
                    logger.info(f"凭证 #{wrapper.id} 已结束休眠，重新加入轮询。")

                wrapper.last_used_time = time.time()
                self.total_requests += 1
                return wrapper
            
            logger.warning("所有凭证都在休眠中。")
            return None

    def report_success(self, wrapper: CredentialWrapper):
        with self.lock:
            wrapper.failure_count = 0

    def report_failure(self, wrapper: CredentialWrapper):
        with self.lock:
            self.total_failures += 1
            wrapper.failure_count += 1
            logger.warning(f"凭证 #{wrapper.id} 失败，当前失败次数: {wrapper.failure_count}")
            if wrapper.failure_count >= self.MAX_FAILURES:
                wrapper.is_resting = True
                wrapper.resting_until = time.time() + self.RESTING_PERIOD
                logger.error(f"凭证 #{wrapper.id} 连续失败 {self.MAX_FAILURES} 次，将休眠 {self.RESTING_PERIOD} 秒。")

    def get_pool_size(self) -> int:
        return len(self.credentials)

    def get_status(self) -> Dict[str, Any]:
        with self.lock:
            pool_status = []
            for wrapper in self.credentials:
                pool_status.append({
                    "id": wrapper.id,
                    "failures": wrapper.failure_count,
                    "is_resting": wrapper.is_resting,
                    "resting_until": time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(wrapper.resting_until)) if wrapper.is_resting else None,
                    "last_used": time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(wrapper.last_used_time)) if wrapper.last_used_time else "Never"
                })
            return {
                "pool_size": self.get_pool_size(),
                "total_requests": self.total_requests,
                "total_failures": self.total_failures,
                "pool_status": pool_status
            }

credential_manager = CredentialManager()
